#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>

int parsing(char line[], char* args[], char type1[], char type2[]);
void command(char* args[], char* path);
void seek(char *arreglo[]);
void changedir(char* args[], char* path);

int main(int argc, char *argv[]){
   
    char* args[100];
    char* logname;    
    char line[1024];
 
    while(1){  
               
        char* path = (char*) getcwd(NULL, 0);   //Encuentra el pwd.
        logname = getenv("LOGNAME");            //Encuentra el logname.
        printf("%s # %s > ",logname,path);      //Imprime el prompt.
                       
        if ( (fgets(line, 1024, stdin) == NULL) || (strcmp(line, "exit\n") == 0) ) return 0;
			else{
                 parsing(line, args, " ", " \n");    //Parsea la linea de entrada.
                 command(args, path);           //interpreta el comando (agrs[0])
            }
    }
       
    return 0;
}

//Parsea una linea
int parsing(char line[], char* args[], char type1[], char type2[]){ 
	int i = 0;
	args[i] = strtok(line, type1);
	
	while((args [i]) != NULL) {
		i++;
		args[i] = strtok (NULL, type2);
	}
	return i;
}

//Interpreta el argumento: si es cd llama a changedir(), si no es cd llama a seek().
void command(char* args[], char* path){
	if( strcmp(args[0], "cd") == 0 ) changedir(args, path);
		else seek(args);
	}

//Cambia el directorio, sea relativo o absoluto
void changedir(char* args[], char* path){
	if( chdir(args[1]) != 0 ) printf("Command not found\n");
		else path = (char*) getcwd(NULL, 0);
}

//Buscaqueda en secuencia PATH,  
void seek(char *args[]){
	char* PATH = getenv("PATH");
    char* directories[100];
    printf("PATH  %s \n", PATH);
    parsing(PATH, directories, ":",":");
    
    //En cada uno de los caminos debo probar si esta el comando 
    int i=0; 
    while( directories[i] != NULL){
		//printf("%s \n",directories[i]);
        printf("%s \n",   strncat(directories[i], strcat (args[0], "/", 1), sizeof(args[0])+1));
        /*if( ( access(  F_OK)) == 0 ){
			directories[i+1] = NULL;
			
			
			} */
        i++;
    }
}
